package com.wangyb.wework.service.contact;

import com.alibaba.fastjson.JSONArray;
import com.wangyb.wework.utils.WxApiUtils;
import com.wangyb.wework.utils.ali.AliyunOssUtils;
import com.wangyb.wework.wxApi.ExternalContactResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: wangyb
 * @Date: 2021/6/30 11:01 下午
 */
@EnableAsync
@Service
public class ExternalContactServiceImpl implements IExternalContactService{
	private static final Logger log = LoggerFactory.getLogger(ExternalContactServiceImpl.class);

	/**
	 * 根据微信成员Id获取成员的客户id
	 * @param wxUserIdList
	 * @param corpId
	 * @return
	 */
	@Override
	public Set<String> getAllExternalUserId(Set<String> wxUserIdList, Long corpId){
		if (wxUserIdList.isEmpty()){
			return Collections.EMPTY_SET;
		}
		Set<String> externalUserIdSet = new HashSet<>();
		wxUserIdList.parallelStream().forEach(wxUserId -> {
			List<String> externalUserIds = getExternalUserId(wxUserId, corpId);
			externalUserIdSet.addAll(externalUserIds);
		});
		return externalUserIdSet;
	}


	/**
	 * 根据微信成员Id获取成员的客户id
	 * @param wxUserId
	 * @param corpId
	 * @return
	 */
	@Override
	public List<String> getExternalUserId(String wxUserId, Long corpId) {
		String respJsonStr = WxApiUtils.getExternalContactList(corpId, wxUserId);
		if (respJsonStr == null){
			return Collections.EMPTY_LIST;
		}
		return JSONArray.parseArray(respJsonStr).toJavaList(String.class);
	}

	@Override
	public Set<ExternalContactResp> getExternalContact(Set<String> externalUserIdSet, Long corpId) {
		Set<ExternalContactResp> set = new HashSet<>();
		if (externalUserIdSet.isEmpty()) {
			return set;
		}
		externalUserIdSet.parallelStream().forEach(externalUserId->{
			ExternalContactResp externalContact = getExternalContact(externalUserId, corpId);
			set.add(externalContact);
		});
		return set;
	}

	/**
	 * 获取客户详细信息
	 * @param externalUserId
	 * @param corpId
	 * @return
	 */
	@Override
	public ExternalContactResp getExternalContact(String externalUserId, Long corpId) {
		ExternalContactResp result = WxApiUtils.getExternalContactInfo(corpId, externalUserId);
		return result;
	}
	@Async
	@Override
	public void uploadContactAvatar(Map<String, String> filePathMap) {
		AliyunOssUtils.multipleUpLoad(filePathMap);
	}

}
